import type {
  ReimbursementApplication,
  ApplicationStatus,
  User,
  ExpenseType,
  ApprovalRecord,
} from '@/services/models'

// 模拟数据库中的数据
let applications: ReimbursementApplication[] = [
  {
    id: 'app-001',
    applicantId: 'user-emp-1',
    applicantName: '员工小王',
    amount: 500,
    description: '购买办公用品',
    expenseType: 'office',
    invoiceInfo: '发票号：INV001，开票日期：2024-01-15',
    status: 'PENDING_HEAD_REVIEW',
    createdAt: new Date(Date.now() - 2 * 3600 * 1000).toISOString(),
    updatedAt: new Date(Date.now() - 2 * 3600 * 1000).toISOString(),
    history: [
      {
        id: 'rec-001',
        approverId: 'user-emp-1',
        approverName: '员工小王',
        action: 'submit',
        comment: '发起申请',
        timestamp: new Date(Date.now() - 2 * 3600 * 1000).toISOString(),
      },
    ],
  },
  {
    id: 'app-002',
    applicantId: 'user-emp-1',
    applicantName: '员工小王',
    amount: 8000,
    description: '客户招待费用',
    expenseType: 'entertainment',
    invoiceInfo: '发票号：INV002，开票日期：2024-01-16',
    status: 'PENDING_FINANCE_REVIEW',
    createdAt: new Date(Date.now() - 3 * 3600 * 1000).toISOString(),
    updatedAt: new Date(Date.now() - 1 * 3600 * 1000).toISOString(),
    history: [
      {
        id: 'rec-002',
        approverId: 'user-emp-1',
        approverName: '员工小王',
        action: 'submit',
        comment: '发起申请',
        timestamp: new Date(Date.now() - 3 * 3600 * 1000).toISOString(),
      },
      {
        id: 'rec-003',
        approverId: 'user-head-1',
        approverName: '部门主管张三',
        action: 'approve',
        comment: '预算内，同意。',
        timestamp: new Date(Date.now() - 1 * 3600 * 1000).toISOString(),
      },
    ],
  },
  {
    id: 'app-003',
    applicantId: 'user-emp-2',
    applicantName: '员工小李',
    amount: 12000,
    description: '购买新服务器',
    expenseType: 'equipment',
    invoiceInfo: '发票号：INV003，开票日期：2024-01-14',
    status: 'REJECTED',
    createdAt: new Date(Date.now() - 5 * 3600 * 1000).toISOString(),
    updatedAt: new Date(Date.now() - 4 * 3600 * 1000).toISOString(),
    history: [
      {
        id: 'rec-004',
        approverId: 'user-emp-2',
        approverName: '员工小李',
        action: 'submit',
        comment: '发起申请',
        timestamp: new Date(Date.now() - 5 * 3600 * 1000).toISOString(),
      },
      {
        id: 'rec-005',
        approverId: 'user-head-1',
        approverName: '部门主管张三',
        action: 'reject',
        comment: '金额过大，需要提供更详细的报价单。',
        timestamp: new Date(Date.now() - 4 * 3600 * 1000).toISOString(),
      },
    ],
  },
]

// 模拟用户数据
export const users: User[] = [
  { id: 'user-emp-1', name: '员工小王', role: 'employee', department: '技术部' },
  { id: 'user-emp-2', name: '员工小李', role: 'employee', department: '市场部' },
  { id: 'user-head-1', name: '部门主管张三', role: 'head', department: '技术部' },
  { id: 'user-fin-1', name: '财务李四', role: 'finance', department: '财务部' },
  { id: 'user-gm-1', name: '总经理赵五', role: 'gm', department: '管理层' },
]

// --- 模拟 API 函数 ---
const DB_KEY = 'workflow-applications'

function saveData() {
  localStorage.setItem(DB_KEY, JSON.stringify(applications))
}

function loadData() {
  const data = localStorage.getItem(DB_KEY)
  if (data) {
    applications = JSON.parse(data)
  } else {
    saveData()
  }
}

// 初始化数据
loadData()

// 模拟网络延迟
const delay = (ms: number) => new Promise((res) => setTimeout(res, ms))

export const api = {
  // 获取所有申请
  async getApplications(): Promise<ReimbursementApplication[]> {
    await delay(300)
    loadData()
    return [...applications]
  },

  // 根据ID获取申请
  async getApplicationById(id: string): Promise<ReimbursementApplication | undefined> {
    await delay(300)
    loadData()
    return applications.find((app) => app.id === id)
  },

  // 提交新申请
  async submitApplication(
    //  // 使用Omit排除id、createdAt、updatedAt字段，因为这些字段由服务端自动生成
    application: Omit<ReimbursementApplication, 'id' | 'createdAt' | 'updatedAt'>,
  ): Promise<ReimbursementApplication> {
    await delay(500) // 模拟网络延迟500毫秒

    const newApplication: ReimbursementApplication = {
      ...application,
      id: `app-${Date.now()}`,
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    }

    applications.push(newApplication)
    saveData()
    return newApplication
  },

  // 更新申请状态
  async updateApplication(
    id: string,
    newStatus: ApplicationStatus,
    record: Partial<ApprovalRecord>,
  ): Promise<ReimbursementApplication> {
    await delay(500)
    const appIndex = applications.findIndex((app) => app.id === id)
    if (appIndex === -1) throw new Error('Application not found')

    const app = applications[appIndex]
    app.status = newStatus
    app.updatedAt = new Date().toISOString()
    app.history.push({
      id: `rec-${Date.now()}`,
      ...record,
      timestamp: new Date().toISOString(),
    })

    applications[appIndex] = app
    saveData()
    return app
  },

  // 重新提交被驳回的申请
  async resubmitApplication(id: string): Promise<ReimbursementApplication> {
    await delay(500)
    const appIndex = applications.findIndex((app) => app.id === id)
    if (appIndex === -1) throw new Error('Application not found')

    const app = applications[appIndex]
    app.status = 'PENDING_HEAD_REVIEW'
    app.updatedAt = new Date().toISOString()
    app.history.push({
      id: `rec-${Date.now()}`,
      approverId: app.applicantId,
      approverName: app.applicantName,
      action: 'submit',
      comment: '重新提交申请',
      timestamp: new Date().toISOString(),
    })

    applications[appIndex] = app
    saveData()
    return app
  },

  // 更新申请数据（编辑后重新提交）
  async updateApplicationData(
    id: string,
    updatedData: {
      applicantName: string
      amount: number
      description: string
      expenseType: ExpenseType
      invoiceInfo?: string
    },
  ): Promise<ReimbursementApplication> {
    await delay(500)
    const appIndex = applications.findIndex((app) => app.id === id)
    if (appIndex === -1) throw new Error('Application not found')

    const app = applications[appIndex]

    // 更新申请数据
    app.applicantName = updatedData.applicantName
    app.amount = updatedData.amount
    app.description = updatedData.description
    app.expenseType = updatedData.expenseType
    app.invoiceInfo = updatedData.invoiceInfo
    app.status = 'PENDING_HEAD_REVIEW'
    app.updatedAt = new Date().toISOString()

    // 添加重新提交记录
    app.history.push({
      id: `rec-${Date.now()}`,
      approverId: app.applicantId,
      approverName: app.applicantName,
      action: 'submit',
      comment: '编辑后重新提交申请',
      timestamp: new Date().toISOString(),
    })

    applications[appIndex] = app
    saveData()
    return app
  },

  // 撤销申请
  async cancelApplication(id: string, comment: string): Promise<ReimbursementApplication> {
    await delay(500)
    const appIndex = applications.findIndex((app) => app.id === id)
    if (appIndex === -1) throw new Error('Application not found')

    const app = applications[appIndex]

    // 检查申请是否可以撤销（只有待审批状态的申请可以撤销）
    if (
      !['PENDING_HEAD_REVIEW', 'PENDING_FINANCE_REVIEW', 'PENDING_GM_REVIEW'].includes(app.status)
    ) {
      throw new Error('只有待审批状态的申请可以撤销')
    }

    app.status = 'CANCELLED'
    app.updatedAt = new Date().toISOString()
    app.history.push({
      id: `rec-${Date.now()}`,
      approverId: app.applicantId,
      approverName: app.applicantName,
      action: 'cancel',
      comment: comment || '申请人撤销申请',
      timestamp: new Date().toISOString(),
    })

    applications[appIndex] = app
    saveData()
    return app
  },

  // 获取用户的申请统计
  async getUserStats(userId: string): Promise<{
    total: number
    pending: number
    completed: number
    rejected: number
  }> {
    await delay(200)
    loadData()

    const userApplications = applications.filter((app) => app.applicantId === userId)

    return {
      total: userApplications.length,
      pending: userApplications.filter((app) =>
        ['PENDING_HEAD_REVIEW', 'PENDING_FINANCE_REVIEW', 'PENDING_GM_REVIEW'].includes(app.status),
      ).length,
      completed: userApplications.filter((app) => app.status === 'COMPLETED').length,
      rejected: userApplications.filter((app) => app.status === 'REJECTED').length,
    }
  },
}
